package com.wn.network.di

import com.blankj.utilcode.util.AppUtils
import com.wn.network.api.ApiInterface
import com.wn.network.constant.BASE_URL
import com.wn.network.interceptor.*
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * @Author: wn
 * @Date: 2024/8/5 16:27
 * @Description: 提供 Retrofit 模块
 */
@Module
@InstallIn(SingletonComponent::class)
object RetrofitModule {

  /**
   * 提供 OkHttpClient
   * @param cookiesInterceptor CookiesInterceptor
   * @param headerInterceptor HeaderInterceptor
   * @param httpLogInterceptor HttpLogInterceptor
   * @param networkInterceptor NetworkInterceptor
   * @param publicParameterInterceptor PublicParameterInterceptor
   * @return OkHttpClient
   */
  @Singleton
  @Provides
  fun provideOkHttpClient(
    cookiesInterceptor: CookiesInterceptor,
    headerInterceptor: HeaderInterceptor,
    publicParameterInterceptor: PublicParameterInterceptor,
    networkInterceptor: NetworkInterceptor,
    httpLogInterceptor: HttpLogInterceptor,
  ): OkHttpClient =
    OkHttpClient.Builder()
      .callTimeout(10, TimeUnit.SECONDS) // 完整请求超时时长，从发起到接收返回数据，默认值0s，不限定
      .connectTimeout(12, TimeUnit.SECONDS) // 与服务器建立连接的时长，默认--10s  秒
      .readTimeout(12, TimeUnit.SECONDS) // 读取服务器返回数据的时长  s
      .writeTimeout(12, TimeUnit.SECONDS) // 向服务器写入数据的时长，默认--10s
/*      .retryOnConnectionFailure(true) // 重连
      .followRedirects(false)// 重定向
      .cache(Cache(File("data/user/0/com.wn.caiiao/cache", "okHttp"), 1024))// 本地缓存
      .cookieJar(LocalCookieKar())// 本地 cookies 持久化存储 */
      .addInterceptor(cookiesInterceptor)
      .addInterceptor(headerInterceptor)
      .addInterceptor(networkInterceptor)
      .addInterceptor(publicParameterInterceptor)
      .addInterceptor(httpLogInterceptor.apply {
        logTag("<wn--Retrofit>")
        if (AppUtils.isAppDebug())
          logLevel(LogLevel.BODY)
        else
          logLevel(LogLevel.BASIC)
      })
      .build()

  /**
   * 提供  Retrofit.Builder
   * @return Retrofit.Builder
   */
  @Singleton
  @Provides
  fun provideRetrofitBuilder(): Retrofit.Builder =
    Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())

  /**
   * 提供  Retrofit
   * @param retrofitBuilder Builder
   * @param okHttpClient OkHttpClient
   * @return Retrofit
   */
  @Singleton
  @Provides
  fun provideRetrofit(retrofitBuilder: Retrofit.Builder, okHttpClient: OkHttpClient): Retrofit =
    retrofitBuilder.baseUrl(BASE_URL).client(okHttpClient).build()

  /**
   * 提供  API
   * @param retrofit Retrofit
   * @return ApiInterface
   */
  @Singleton
  @Provides
  fun provideApi(retrofit: Retrofit): ApiInterface = retrofit.create(ApiInterface::class.java)
}